<template>
  <div class="buy">
    <nav-bar>
      <div slot="title">购买</div>
    </nav-bar>

    <scroll class="scroll" ref="scroll">
      <user class="user" @click.native="changeAddress" @changeData="changeData"></user>
      <list :goods="goods"></list>
    </scroll>
    <account class="account" :totalPrice="dataPrice" @click.native="buy"></account>
  </div>
</template>

<script>
  import navBar from '../profile/detail/components/navBar.vue'
  import scroll from 'components/common/scroll/scroll.vue'

  import user from './components/info.vue'
  import list from './components/goodsList.vue'
  import account from './components/summary.vue'
  import {addOrder} from 'network/order/order.js'
  import {carDelData} from 'network/car/emit.js'
  export default{
    name:'',
    data(){
      return {
        dataPrice:0,
        goods:[],
        userId:JSON.parse(window.sessionStorage.user).id,
        userName:JSON.parse(window.sessionStorage.user).username,
        tel:JSON.parse(window.sessionStorage.user).tel,
        address:JSON.parse(window.sessionStorage.user).address
       }
    },
    methods:{
      changeAddress(){
        this.$router.push('/address')
      },
      buy(){
        for(let i of this.goods){
          if(i.price.charAt(0)<=0||i.price.charAt(0)>=9){
            i.price=i.price.slice(1)
          }
          i.userId=JSON.parse(window.sessionStorage.user).id
          i.userName=JSON.parse(window.sessionStorage.user).username
          i.tel=this.tel
          i.address=this.address
          delete i.id
        }
        console.log(this.goods);
        addOrder(this.goods).then(res=>{
          console.log("add",res);
          if(res.data.result=="yes"){
            for(let i of this.goods){
              carDelData(i.userId,i.goodId)
            }
            this.$router.push('/userOrder')
          }
        }).catch(e=>{
          console.log(e);
        })
      },
      changeData(info){
        this.username=info.userName
        this.tel=info.tel
        this.address=info.address
      }
    },
    components:{
      navBar,scroll,user,list,account
    },
    activated() {
      this.$bus.$on('sendGoodToBuy',res=>{
        console.log('buy',res);
        this.goods=res
      })
      this.goods=JSON.parse(window.sessionStorage.buyGood)

      let price=0
      for(let i of this.goods){
        if(isNaN(Number(i.price.charAt(0)))){
          i.price=i.price.slice(1)
        }
        price+=Number(i.price)
      }
      this.dataPrice=price
    }
  }
</script>

<style scoped>
  .buy{

  }
  .scroll{
    height: calc(100vh - 44px - 49px - 40px);
    position: relative;
    overflow: hidden;
    background-color: #dfdfdf;
    /* top: 44px; */
  }
  .account{
    height: 40px;
    line-height: 40px;
  }
  .user{
    margin: 10px auto;
  }
</style>
